package controller.wechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import service.Impl.WsParseXML;
import util.aes.AesException;
import util.aes.SHA1;
import util.api.ApIURL;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 * Created by thinkjoy on 2017/8/29.
 * 微信对接入口
 */
@Controller
public class WeChatApplicationController {

    @Autowired
    private WsParseXML wsParseXML;

    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
    public void WechatApplication(@RequestParam("signature") String signature,
                                     @RequestParam("timestamp") String timestamp,
                                     @RequestParam("nonce") String nonce,
                                     @RequestParam("echostr") String echostr,HttpServletResponse response) {
        String autograph;
        try {
            autograph= SHA1.getSHA1(ApIURL.TOKEN,timestamp,nonce);
            if (autograph.equals(signature)){
                response.getWriter().print(echostr);
            }
        } catch (AesException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收微信返回的xml消息包
     * @param xmlmsg
     * @param response
     * @throws JAXBException
     * @throws IOException
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
    public void WechatApplication(@RequestBody String xmlmsg,HttpServletResponse response) throws JAXBException, IOException, URISyntaxException {
        wsParseXML.getbasemsg(xmlmsg,response);
    }
}
